package net.niufei.filter;

import net.niufei.Packet;
import net.niufei.SessionFilter;
import net.niufei.SessionFilterChain;

public abstract class AbstractSessionFilterChain implements SessionFilterChain {

	private static final SessionFilter NULL_FILTER = new NullSessionFilter();
	
	
	protected abstract SessionFilter nextFilter();
	

	private SessionFilter next() {
		SessionFilter filter = nextFilter();
		return filter == null ? NULL_FILTER : filter;
	}
	
	@Override
	public void sessionStarted() {
		try {
			next().sessionStarted(this);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void sessionClosed() {
		try {
			next().sessionClosed(this);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void sessionTimeout() {
		try {
			next().sessionTimeout(this);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void packetReceived(Packet packet) {
		try {
			next().packetReceived(this, packet);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void objectReceived(Object obj) {
		try {
			next().objectReceived(this, obj);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void packetSend(Packet packet) {
		try {
			next().packetSend(this, packet);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void packetSent(Packet packet) {
		try {
			next().packetSent(this, packet);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void objectSent(Object obj) {
		try {
			next().objectSent(this, obj);
		} catch (Exception e) {
			exceptionCaught(e);
		}
	}

	@Override
	public void exceptionCaught(Throwable cause) {
		getSession().getSessionFilterChain(false).exceptionCaught(cause);
	}

}
